package com.beigai.imessage.message.action;

import com.alibaba.druid.util.StringUtils;
import com.beigai.imessage.common.util.MD5Util;
import com.beigai.imessage.common.util.UUIDUtil;
import com.beigai.imessage.dao.mapper.ext.UserImagePOMapperExt;
import com.beigai.imessage.dao.po.UserImagePO;
import com.beigai.imessage.server.UserSession;
import com.beigai.imessage.session.CurrentUserSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

/**
 * Created by xxl on 2017/5/17.
 */
@RestController
public class FileAction {
    @Value("${image.savePath}")
    private String savePath;

    @Autowired
    private UserImagePOMapperExt userImagePOMapperExt;

    /**
     * 文件上传具体实现方法（单文件上传）
     *
     * @param file
     * @return
     */
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public String upload(@RequestParam("file") MultipartFile file) {
        if (!file.isEmpty()) {
            try {
                String newFileName = getRealFileName(file);
                return newFileName;
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return "上传失败," + e.getMessage();
            } catch (IOException e) {
                e.printStackTrace();
                return "上传失败," + e.getMessage();
            }
        } else {
            return "上传失败，因为文件是空的.";
        }
    }

    /**
     * 获取文件的真实路径
     *
     * @param file
     * @return
     * @throws IOException
     */
    private String getRealFileName(@RequestParam("file") MultipartFile file) throws IOException {
        String newFileName;
        String fileMD5 = MD5Util.getFileMD5String((FileInputStream) file.getInputStream());
        newFileName = userImagePOMapperExt.queryByMd5(fileMD5);
        if (StringUtils.isEmpty(newFileName)) {
            newFileName = UUIDUtil.generatorUUID();
        }
        String originalFilename = file.getOriginalFilename();
        UserImagePO record = new UserImagePO();
        record.setFileMd5(fileMD5);
        record.setOriginalFileName(originalFilename);
        record.setRealFileName(newFileName);
        UserSession userSession = CurrentUserSession.get();
        if (userSession != null) {
            record.setUserCode(userSession.getCode());
        }
        userImagePOMapperExt.insertSelective(record);
        file.transferTo(new File(savePath + newFileName));
        return newFileName;
    }

    /**
     * 多文件上传 主要是使用了MultipartHttpServletRequest和MultipartFile
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/upload/batch", method = RequestMethod.POST)
    public String batchUpload(HttpServletRequest request) {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        MultipartFile file = null;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < files.size(); ++i) {
            file = files.get(i);
            if (!file.isEmpty()) {
                try {
                    String realFileName = getRealFileName(file);
                    sb.append(realFileName + ",");
                } catch (Exception e) {
                    return "You failed to upload " + i + " => " + e.getMessage();
                }
            } else {
                return "You failed to upload " + i + " because the file was empty.";
            }
        }
        sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }

    /**
     * 下载文件
     *
     * @param filename
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/down", method = RequestMethod.GET)
    public ResponseEntity<InputStreamResource> downloadFile(String filename)
            throws IOException {
        String filePath = savePath + filename;
        FileSystemResource file = new FileSystemResource(filePath);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getFilename()));
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");

        return ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(file.contentLength())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new InputStreamResource(file.getInputStream()));
    }
}

